package com.design.pattern.behavior.iterator.general;

import java.util.ArrayList;
import java.util.List;

public class Test {
    //抽象迭代器
    public interface Iterator<E> {
        E next();
        boolean hasNext();
    }
    //具体迭代器
    public static class ConcreteIterator<E> implements Iterator<E> {
        private List<E> list;
        private int cursor = 0;

        public ConcreteIterator(List<E> list) {
            this.list = list;
        }

        @Override
        public E next() {
            return this.list.get(cursor++);
        }

        @Override
        public boolean hasNext() {
            return this.cursor < this.list.size();
        }
    }
    //抽象容器
    public interface IAggregate<E> {
        boolean add(E e);
        boolean remove(E element);
        Iterator<E> iterator();
    }

    //具体容器
    public static class ConcreteAggregate<E> implements IAggregate<E> {
    private List<E> list = new ArrayList<>();

        @Override
        public boolean add(E e) {
            return this.list.add(e);
        }

        @Override
        public boolean remove(E element) {
            return this.list.remove(element);
        }

        @Override
        public Iterator<E> iterator() {
            return new ConcreteIterator<E>(this.list);
        }
    }

    public static void main(String[] args) {
        //创建一个容器对象
        IAggregate<String> aggregate = new ConcreteAggregate<>();
        //添加元素
        aggregate.add("a");
        aggregate.add("b");
        aggregate.add("c");
        //获取容器对象迭代器
        Iterator<String> iterator = aggregate.iterator();
        //遍历
        while(iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

}
